<script>
  import { onMount } from "svelte";
  import { GuestKeepAlive,RegKeepAlive } from "./wshandle";

  let userdata = [];
  let conn = null;


  let fileInput;
let isexit = false;
let result;
let imgURL = "123";

async function getAvater(){
      const response = await fetch('/api/getavater', { // '/upload' 是后端的接收上传文件的端点
        method: 'GET',
      })
      .then(response => response.arrayBuffer()).then((data) => {
            // 检查返回的数据是否为空
            if (!data) {
                console.error("data is null");
                throw new Error("data is null");
            }
            // 检查返回的数据是否为ArrayBuffer
            if (!(data instanceof ArrayBuffer)) {
                console.error("data is invalid");
                throw new Error("data is invalid");
            }
            console.log(result);
            // 将返回的数据存入personalInfo
            result = data;
            if (result === undefined || result === null) {
                throw new Error("Failed to get personal avatar");
            } else if (!(result instanceof ArrayBuffer)) {
                throw new Error(" get personal avatar type error");
            }
            const blob = new Blob([result], { type: "image/jpg" });
            imgURL = URL.createObjectURL(blob);
            console.log("成功显示！")
            isexit = true
        }).catch((error) => {
            console.error("fetch error", error);
            throw error;
        });

}

  onMount(async () => {
    const response = await fetch(`/api/GuestLogin`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include",
    });
    if (response.status == 251 || response.status === 254) {
      //也就是此时处于游客登录，就可以从浏览器中获取这个token
      const token = await getTokenFromCookie(100);
      if (token === null) {
        console.error("Start session err: token is null");
        throw new Error("Start session err: token is null");
      }
      console.log("游客成功登录，你的token值为", token);
      conn = new GuestKeepAlive(token);
    }
    else if (response.status == 255){
 //也就是此时处于游客登录，就可以从浏览器中获取这个token
 const token = await getTokenFromCookie(100);
      if (token === null) {
        console.error("Start session err: token is null");
        throw new Error("Start session err: token is null");
      }
      console.log("注册用户成功登录，你的token值为", token);
      conn = new RegKeepAlive(token);
    }
    else if (response.status === 256){
      console.error("token令牌过期了。请重新登录！")
    }
  });

  async function Testclose() {
    if (conn == null) {
      console.log("cannot take action to websocket!");
      return;
    }
    conn.testclose();
  }

  async function GetActiveUser() {
    try {
      const response = await fetch(`/api/GetActiveUsers`, {
        method: "GET",
        credentials: "include",
      });
      if (response.status == 254) {
        const data = await response.json();
        userdata = data;
      }
    } catch (e) {
      console.error("Error fetching userdata");
    }
  }

  async function getTokenFromCookie(timeout) {
    await new Promise((resolve) => {
      setTimeout(resolve, timeout);
    });
    let token = null;
    try {
      const cookies = document.cookie.split("; ");
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i];
        const [name, value] = cookie.split("=");
        if (name === "token") {
          token = value;
          return token;
        }
      }
      return null;
    } catch (error) {
      console.error("getSessionIDFromCookie Err:", error);
      throw new Error("Fail to get sessionID from cookie: " + error);
    }
  }

  let email = "";
  let password = "";
  function handleKeyDown(event) {
    if (event.key === "Enter" && !isLoading) {
      //调用登录函数
      handleLogin();
    }
  }

  async function handleLogin() {
    try {
      const response = await login(email,password);
      if (response==="failed login"){
         console.error(response)
      }
    } catch (e) {
      console.error(e)
    }
  }

  async function login(email, password) {
    // 检查email是否为空
    if (email === null) {
      throw new Error("email is null");
    }
    // 检查pwd是否为空
    if (password === null) {
      throw new Error("password is null");
    }

    // 检查email是否为字符串
    if (typeof email !== "string") {
      throw new Error("email is not a string");
    }
    // 检查pwd是否为字符串
    if (typeof password !== "string") {
      throw new Error("pwd is not a string");
    }
    try{
      const responseLogin = await fetch("/api/UserLogin",{
        method:"POST",
        headers:{
          "Content-Type": "application/json",
        },
        body:JSON.stringify({
          email:email,
          password:password
        })
      })
      switch(responseLogin.status){
          case 253:
              const token = await getTokenFromCookie(10)
              if(token===""){
                console.error("login:token is nil")
                throw new Error("login:token is nil")
              }
              await new RegKeepAlive(token)
            return "Login successfully"
          default:
              console.error("failed to login",responseLogin.status)
              const err = await responseLogin.text()
              console.error(err)
              return "failed login"
        }
    }catch(e){
      console.error("Login err:", e);
      throw e;
    }
  }
</script>

<button on:click={GetActiveUser} class="write-btn" title="写意见"
  >点击获取目前在线用户</button
>

<button on:click={Testclose} title="写意见">关闭自己的连接</button>

<input type="email" class= "input-field" placeholder="输入邮箱" bind:value={email} />
<input
  class= "input-field"
  type="password"
  placeholder="输入密码"
  bind:value={password}
  on:keydown={handleKeyDown}
/>

<button on:click={handleLogin}></button>

{#if userdata.length === 0}
  <p class="nohistorytext">目前无在线玩家</p>
{:else}
  {#each userdata as item}
    <li>{item}</li>
  {/each}
{/if}

<button on:click={getAvater}>显示头像</button>
{#if isexit}
  <img src={imgURL} alt="头像"/>
{/if}

<style>
  .nohistorytext {
    text-align: center; /* 文本居中 */
    font-size: 1.5em; /* 字体大小 */
    color: #000000; /* 字体颜色 */
    margin: 60px 0; /* 上下边距 */
    font-weight: bold; /* 粗体 */
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.7); /* 文本阴影 */
  }
  .write-btn {
    width: 100px; /* 每个按钮占满整个宽度 */
    height: 100px;
    background: none;
    justify-content: center;
    align-items: center;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    font-size: 1.2rem; /* 增加字体大小 */
    background-image: url(../../lib/images/girl.png);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  }
  .input-field{
    background-color: #f0f0f0;
  color: #333;
    position: relative;
    width: 16vw;
    height: auto;
    margin:0.5vw 0; /*外边距*/
    /* margin-bottom: 1rem; */
    text-align: center;
    font-size: 1.3vw;
    padding: 0.8vw; /*内边距*/
    border: 0.3vw solid rgba(59,149,200);
    border-radius:15px ;
    transition: 0.3s ease;
    /* position:absolute; */
    /* top:20%; */
    /* left: 45%; */
  }
</style>
